package com.mnsq.subject.service.impl;

import com.mnsq.common.bean.dto.PageInfo;
import com.mnsq.common.tools.jpa.JpaExample;
import com.mnsq.subject.bean.condition.SubjectCondition;
import com.mnsq.subject.bean.condition.UserOperateCondition;
import com.mnsq.subject.bean.entity.Subject;
import com.mnsq.subject.bean.entity.UserCollect;
import com.mnsq.subject.bean.entity.UserGreat;
import com.mnsq.subject.dao.CollectRepository;
import com.mnsq.subject.dao.GreatRepository;
import com.mnsq.subject.dao.SubjectContentRepository;
import com.mnsq.subject.dao.SubjectRepository;
import com.mnsq.subject.service.SubjectService;
import com.mnsq.user.bean.base.ThreadLocalInfo;
import com.mnsq.user.bean.dto.LoginInfo;
import com.mnsq.user.bean.entity.User;
import com.mnsq.user.dao.UserRepository;
import com.vwkit.common.bean.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

/**
 * @author Administrator
 * @date 2019/3/17 0017
 */
@Service
public class SubjectServiceImpl implements SubjectService {
    @Autowired
    private SubjectRepository subjectRepository;
    @Autowired
    private SubjectContentRepository subjectContentRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private GreatRepository greatRepository;
    @Autowired
    private CollectRepository collectRepository;

    @Override
//    @AutoCache(cacheType = AutoCache.CacheType.MINS, value = 30, prefix = "subject", cls = PageInfo.class)
    public PageInfo<Subject> queryPageByCondition(SubjectCondition subjectCondition) {
        PageInfo<Subject> info = new PageInfo<>();
        Page<Subject> all = subjectRepository.findAll(JpaExample.getInstance().getExample(subjectCondition, subjectCondition.getInstance()), PageRequest.of(subjectCondition.getPageNum(), subjectCondition.getPageSize(), Sort.by("createTime").descending()));
        for (Subject sj : all) {
            if (sj.getCreateUserId() == null) {
                continue;
            }
            Optional<User> usr = userRepository.findById(sj.getCreateUserId());
        }
        info.setContent(all.getContent())
                .setTotalPages(all.getTotalPages())
                .setPageNum(subjectCondition.getPageNum())
                .setTotalSize(all.getTotalElements());
        return info;
    }

    @Override
//    @AutoCache(fixedValue = false, renew = true, cls = SubjectMg.class, prefix = "detail")
    public Subject queryByUnique(String unique) {
        SubjectCondition sc = new SubjectCondition();
        sc.setStatus(null);
        sc.setUnique(unique);
        Optional<Subject> one = subjectRepository.findOne(JpaExample.getInstance().getExample(sc, sc.getInstance()));
        if (one.isPresent() && one.get().getSubjectContentId() != null) {
            Subject subject = one.get();
            // todo
            subject.setSubjectContent(subjectContentRepository.findById(one.get().getSubjectContentId()).orElse(null));
            return subject;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result great(String unique) {
        LoginInfo loginInfo = ThreadLocalInfo.LOGIN_INFO.get();
        // 查询是否已点赞
        UserOperateCondition uc = new UserOperateCondition().setUserId(loginInfo.getUserId());
        uc.setUnique(unique);
        UserGreat userGreat = uc.toGreat();
        Optional<UserGreat> one = greatRepository.findOne(JpaExample.getInstance().getExample(uc, userGreat));
        boolean present = false;
        // 已点赞，则删除点赞
        if (one.isPresent()) {
            UserGreat ut = one.get();
            greatRepository.delete(ut);
            present = true;
        } else {
            // 未点赞，则保存点赞记录
            UserGreat ugs = new UserGreat();
            ugs.setUserId(loginInfo.getUserId());
            ugs.setUnique(unique);
            ugs.setCreateTime(new Date());
            greatRepository.save(ugs);
        }
        updateTimes(GREAT, unique, present ? -1 : 1);
        return Result.success(present ? "取消点赞成功" : "点赞成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result collect(String unique) {
        LoginInfo loginInfo = ThreadLocalInfo.LOGIN_INFO.get();
        UserOperateCondition uoc = new UserOperateCondition().setUserId(loginInfo.getUserId());
        uoc.setUnique(unique);
        Optional<UserCollect> one = collectRepository.findOne(JpaExample.getInstance().getExample(uoc, uoc.toCollect()));
        boolean present = false;
        // 已收藏，则删除收藏
        if (one.isPresent()) {
            UserCollect uc = one.get();
            collectRepository.delete(uc);
            present = true;
        } else {
            // 未收藏，则保存收藏记录
            UserCollect ugs = new UserCollect();
            ugs.setUserId(loginInfo.getUserId());
            ugs.setUnique(unique);
            ugs.setCreateTime(new Date());
            collectRepository.save(ugs);
        }
        updateTimes(COLLECT, unique, present ? -1 : 1);
        return Result.success(present ? "取消收藏成功" : "收藏成功");
    }

    @Override
    public Subject queryUserInfoByUnique(String unique) {
        LoginInfo loginInfo = ThreadLocalInfo.LOGIN_INFO.get();
        Subject subject = new Subject();
        if (loginInfo != null) {
            UserOperateCondition uoc = new UserOperateCondition().setUserId(loginInfo.getUserId());
            uoc.setUnique(unique);
        }
        return subject;
    }

    private String GREAT = "A";
    private String COLLECT = "B";
    public static String READ = "C";
    public static String COMMENT = "D";

    /**
     * 更新次数
     *
     * @param type   A:点赞；B:收藏；C:阅读量；D:评论数
     * @param unique
     * @param times
     */
    private void updateTimes(String type, String unique, int times) {
        SubjectCondition subject = new SubjectCondition();
        subject.setUnique(unique);
        Optional<Subject> sj = subjectRepository.findOne(JpaExample.getInstance().getExample(subject, subject.getInstance()));
        if (!sj.isPresent()) {
            return;
        }
        Subject st = sj.get();
        // 根据是否存在点赞信息，判断加减数量
        subjectRepository.save(st);
    }

    /**
     * 查询某个记录的类型：文章、例题、经验等
     *
     * @param unique
     * @return
     */
    private Integer queryType(String unique) {
        SubjectCondition sc = new SubjectCondition();
        sc.setUnique(unique);
        Optional<Subject> one = subjectRepository.findOne(JpaExample.getInstance().getExample(sc, sc.getInstance()));
        if (one.isPresent()) {
            return one.get().getType();
        }
        return 0;
    }
}
